/********************************************/
// Creation History
// --------------------------------------------------------------
//	Company:			HTHK
//	NAME:				TssEmployeeImport.java
//    Title   :			Employee Maintenance
//	FUNCTION:           Import information of Employee from HRMS
//	BY:					Tiger Wang
//	DATE:				19/12/2003
// --------------------------------------------------------------
/*********************************************/

package tss.upload;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.StringTokenizer;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tss.common.DBServlet2;
import tss.staffproject.EmployeeBean;
import tss.staffproject.EmployeeProcess;

import com.ffpc.sql.DataException;
import com.ffpc.struts.StrutsMessage;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

public class TssEmployeeImport extends DBServlet2 {

	// Change a string of Date from "yyyy-MM-dd" to "dd/MM/yyyy"
	private String formatDate(String as_OrialDate) {
		String ls_Delimiter = "/";

		StringTokenizer lSt_Date = new StringTokenizer(as_OrialDate, "-");
		String ls_Year = (String) lSt_Date.nextElement();
		String ls_Month = (String) lSt_Date.nextElement();
		String ls_Day = (String) lSt_Date.nextElement();

		// If length of Month and Day is not 2, add a "0" before it.
		if (ls_Month.length() < 2)
			ls_Month = "0" + ls_Month;
		if (ls_Day.length() < 2)
			ls_Day = "0" + ls_Day;

		String ls_RtnDate = ls_Day + ls_Delimiter + ls_Month + ls_Delimiter
				+ ls_Year;

		return ls_RtnDate;
	}

	// The data imported is formated as "***", the first and last quotation
	// marks must be deleted.
	private String formatImportData(String as_importData) {
		int li_len = as_importData.length();
		String ls_rtnData = as_importData.substring(1, li_len - 1);

		return ls_rtnData;
	}

	@Override
	protected String perform(HttpServletRequest request,
			HttpServletResponse response, StrutsMessage message)
			throws ServletException, IOException, SQLException, DataException,
			Exception {
		ResultSet resultSet = null;
		Statement statement = null;
		Connection connection = null;

		String upload_file = null;
		com.jspsmart.upload.File file = null;

		connection = this.getConnection();
		statement = connection.createStatement();

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		String ls_ReturnMsg = "Import data successfully!";

		try {
			SmartUpload mySmartUpload = new SmartUpload();
			ServletConfig config = null;
			// Initialization
			mySmartUpload.initialize(config, request, response);

			// Upload
			mySmartUpload.upload();

			// Get file name
			file = mySmartUpload.getFiles().getFile(0);

			String str = file.getContentString();
			StringTokenizer lSt_EmployeeList = new StringTokenizer(str, "\r\n");

			// Do not import first line because it's titles.
			if (lSt_EmployeeList.hasMoreElements())
				lSt_EmployeeList.nextElement();

			// Every line is a Employee record.
			while (lSt_EmployeeList.hasMoreElements()) {
				String ls_Employee = (String) lSt_EmployeeList.nextElement();
				StringTokenizer lSt_EmplColumn = new StringTokenizer(
						ls_Employee, ",");

				// Check number of column. It should be 12(11 column of table,
				// and rowid generated by DB itself).
				// If not, don't import data and give an error message out.
				int li_length = lSt_EmplColumn.countTokens();
				if (12 != li_length) {

					ls_ReturnMsg = "Format of file is error, please check it!";

				} else {
					// Do not import first column because it's rowid which is
					// generated by DB itself.
					if (lSt_EmplColumn.hasMoreElements())
						lSt_EmplColumn.nextElement();

					while (lSt_EmplColumn.hasMoreElements()) {
						EmployeeBean lEB_EmplBean = EmployeeProcess
								.createBean();

						// STAFF_NO
						lEB_EmplBean
								.setStaff_no(formatImportData((String) lSt_EmplColumn
										.nextElement()));

						// Find if there is a record has same "STAFF NO" in DB.
						EmployeeBean[] lAr_StaffList = EmployeeProcess.find(
								this.getConnection(), lEB_EmplBean);
						boolean lbl_UpdateEmpl = false;
						if (0 < lAr_StaffList.length)
							lbl_UpdateEmpl = true;

						// SURNAME
						lEB_EmplBean
								.setSurname(formatImportData((String) lSt_EmplColumn
										.nextElement()));
						// FIRST_NAME
						lEB_EmplBean
								.setFirst_name(formatImportData((String) lSt_EmplColumn
										.nextElement()));
						// ALIAS
						lEB_EmplBean
								.setAlias(formatImportData((String) lSt_EmplColumn
										.nextElement()));
						// JOIN_DATE
						String ls_JoinDate = formatImportData((String) lSt_EmplColumn
								.nextElement());
						if (0 < ls_JoinDate.length()) {
							lEB_EmplBean.setJoin_date(formatDate(ls_JoinDate));
						}
						// LAST_DATE
						String ls_LastDate = formatImportData((String) lSt_EmplColumn
								.nextElement());
						if (0 < ls_LastDate.length()) {
							lEB_EmplBean.setLast_date(formatDate(ls_LastDate));
						}
						// DEPARTMENT_CODE
						lEB_EmplBean
								.setDepartment_code(formatImportData((String) lSt_EmplColumn
										.nextElement()));
						// COST_CENTER
						lEB_EmplBean
								.setCost_center(formatImportData((String) lSt_EmplColumn
										.nextElement()));
						// POSITION
						lEB_EmplBean
								.setPosition(formatImportData((String) lSt_EmplColumn
										.nextElement()));
						// EMPLOYMENT_TYPE
						lEB_EmplBean
								.setEmployment_type(formatImportData((String) lSt_EmplColumn
										.nextElement()));
						// IMPORT_DT
						String ls_ImportDate = formatImportData((String) lSt_EmplColumn
								.nextElement());
						if (0 < ls_ImportDate.length()) {
							lEB_EmplBean
									.setImport_dt(formatDate(ls_ImportDate));
						}

						if (true == lbl_UpdateEmpl) {
							// Update Employee record.
							EmployeeProcess.update(this.getConnection(),
									lEB_EmplBean);
						} else {
							// Insert Employee record.
							EmployeeProcess.insert(this.getConnection(),
									lEB_EmplBean);
						}
					}
				}
			}
		} catch (SmartUploadException se) {
			System.out.println(se);
			ls_ReturnMsg = "Exception during importing, please retry!";
		}

		message.setMessage(ls_ReturnMsg);

		return "tss/upload/tssupload.jsp";
	}
}
